package com.socool.sinofaith.ui;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.socool.sinofaith.R;
import com.socool.sinofaith.SocoolApplication;
import com.socool.sinofaith.adapter.AuditRefusedAdapter;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.RefuseTaskMessage;
import com.socool.sinofaith.util.ConstansJsonUrl;
import com.socool.sinofaith.util.SinofaithUtil;
import com.socool.sinofaith.view.LoadingDialog;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

public class AuditRefusedFragment extends Fragment {

	private PullToRefreshListView mPullRefreshListView;
	private ListView listView;
	private AuditRefusedAdapter refusedAdapter;
	private int currentIndex = 1;
	// 定位相关
	LocationClient mLocClient;
	boolean isFirstLoc = true;// 是否首次定位
	public MyLocationListenner myListener;
	private LatLng mLatLng;

	private LoadingDialog mLoadingDialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_auditrefused, null);
		SocoolApplication.addActivity(this.getActivity());
		mLoadingDialog = new LoadingDialog(this.getActivity());

		mPullRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listview);
		// 定位初始化
		mLocClient = new LocationClient(getActivity());
		myListener = new MyLocationListenner();
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		mLocClient.setLocOption(option);
		mLocClient.start();
		return view;
	}

	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude()).longitude(location.getLongitude()).build();
			if (isFirstLoc) {

				isFirstLoc = false;
				mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
				SinofaithUtil.GPS = location.getLatitude() + "," + location.getLongitude();
			}
		}

		public void onReceivePoi(BDLocation poiLocation) {

		}

	}

	void init() {
		refusedAdapter = new AuditRefusedAdapter(this.getActivity());
		listView = mPullRefreshListView.getRefreshableView();
		listView.setAdapter(refusedAdapter);

		mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(AuditRefusedFragment.this.getActivity(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// 清空数据重新请求
				refusedAdapter.getMdatas().clear();
				currentIndex = 1;
				getData();
			}
		});
		mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
			@Override
			public void onLastItemVisible() {
				// lastLoadingView.setVisibility(View.VISIBLE);
				currentIndex++;
				getData();
			}
		});

		// 清空数据重新请求
		refusedAdapter.getMdatas().clear();
		currentIndex = 1;
		getData();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		MainActivity.imageview.setVisibility(View.VISIBLE);
		MainActivity.imageview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// 清空数据重新请求
				refusedAdapter.getMdatas().clear();
				currentIndex = 1;
				getData();
			}
		});
		super.onActivityCreated(savedInstanceState);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void getData() {
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.refuseTask_url);
		params.put("did", SinofaithUtil.did);
		params.put("mobile", getSPString());
		// params.put("mobile", "13400000000");
		fh.get(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mLoadingDialog.show();
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				mLoadingDialog.dismiss();
				super.onSuccess(t);
				try {
					RefuseTaskMessage refuseTaskMessage = HttpJsonAdapter.getInstance().get(t.toString(), RefuseTaskMessage.class);
					if ("0".equals(refuseTaskMessage.getResult())) {
						refusedAdapter.setMdatas(refuseTaskMessage.getRefuseTaskList());
					}

					mPullRefreshListView.onRefreshComplete();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				mLoadingDialog.dismiss();
				super.onFailure(t, errorNo, strMsg);
				Toast.makeText(AuditRefusedFragment.this.getActivity(), strMsg, Toast.LENGTH_LONG).show();
			}

		});
	}

	@Override
	public void onResume() {
		// 清空数据重新请求
		init();
		super.onResume();
	}
	
	private String getSPString(){
		SharedPreferences sp=getActivity().getSharedPreferences("login", Context.MODE_PRIVATE);
		return sp.getString("UserMobile", "");
	}
}
